<template>
  <n-grid x-gap="10" y-gap="10" :col="24">
    <n-gi span="6" v-for="product in prodcutsList" :key="product.id">
      <div
        class="custom-choose-item flex items-center justify-center"
        @click.stop="handleSelectProduct(product)"
      >
        <div class="image">
          <n-image
            preview-disabled
            width="56"
            height="56"
            :src="product.image"
            fallback-src="https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg"
          />
        </div>
        <div class="title">
          <span> {{ product.name }} </span>
        </div>
      </div>
    </n-gi>
  </n-grid>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { debounce, get } from "lodash-es";
import { getProducts } from "@/api/product/product.api";
import { Product } from "@/types/model/product/vos/product.vo";
import { IChooseModelProps } from "./props";

const emits = defineEmits(["selected"]);

const props = withDefaults(defineProps<IChooseModelProps>(), {
  brandId: "",
  categoryId: "",
});

const initLoading = ref<boolean>(true);
const prodcutsList = ref<Product[]>([]);

const handleGetProducts = async () => {
  initLoading.value = true;
  try {
    const res = await getProducts({
      page: 1,
      pageSize: 9999,
      categoryId: props.categoryId,
      brandId: props.brandId,
      canTradein: "1",
    });

    prodcutsList.value = get(res, "result.records") || [];
  } finally {
    initLoading.value = false;
  }
};

const handleSelectProduct = debounce(function (payload: Product) {
  emits("selected", payload);
}, 200);

const init = () => {
  handleGetProducts();
};

onMounted(() => {
  init();
});
</script>
